package com.youaishujuhui.devops.web.controller.manage;

//import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youaishujuhui.devops.web.domain.manage.SysRole;
import com.youaishujuhui.devops.web.domain.manage.SysUser;
import com.youaishujuhui.devops.web.service.manage.SysRoleService;
import com.youaishujuhui.devops.web.service.manage.SysUserService;
import com.youaishujuhui.devops.web.vo.Page;
import com.youaishujuhui.devops.web.vo.Result;

//import com.youaishujuhui.devops.gamesys.po.manage.SysUserChannelServerLimitPO;
//import com.youaishujuhui.devops.gamesys.po.manage.SysUserPO;
//import com.youaishujuhui.devops.gamesys.service.dict.ChannelServerService;
//import com.youaishujuhui.devops.gamesys.service.manage.SysUserChannelServerLimitService;
//import com.youaishujuhui.devops.gamesys.service.manage.SysUserProductRoleService;
//import com.youaishujuhui.devops.gamesys.service.manage.SysUserService;
//import com.youaishujuhui.devops.gamesys.vo.Page;
//import com.youaishujuhui.devops.gamesys.vo.Result;
//import com.youaishujuhui.devops.gamesys.vo.ZTreeNode;
//import com.youaishujuhui.devops.gamesys.vo.dict.BigChannel;
//import com.youaishujuhui.devops.gamesys.vo.dict.Channel;
//import com.youaishujuhui.devops.gamesys.vo.dict.Server;
//import com.youaishujuhui.devops.gamesys.vo.dict.SmallChannel;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/manage/user")
public class SysUserController {

	  @Autowired
	  private SysUserService sysUserService;
	  
	  @Autowired
	  private SysRoleService sysRoleService;
	  
//
//    @Autowired
//    private SysUserProductRoleService sysUserProductRoleService;
//
//    @Autowired
//    private ChannelServerService channelServerService;
//
//    @Autowired
//    private SysUserChannelServerLimitService sysUserChannelServerLimitService;

    @RequestMapping("/page")
    public ModelAndView page(HttpServletRequest request) {
        return new ModelAndView("manage/user");
    }

    @RequestMapping("/query")
    @ResponseBody
    public Result<List<SysUser>> query(Integer limit, Integer offset, String sort, String order, String searchName) {
        Map<String, Object> param = new HashMap<>();
        param.put("limit", limit);
        param.put("offset", offset);
        param.put("sort", sort);
        param.put("order", order);
        param.put("searchName", searchName);
        Result<List<SysUser>> result = new Result<>();
        int total = sysUserService.total(param);

        List<SysUser> list = sysUserService.query(param);
        Page page = new Page(total, limit);
        result.setPage(page);
        result.setData(list);
        result.setCode(Result.SUCCESS);

        return result;
    }
    
    @RequestMapping("/getRolesList")
    @ResponseBody
    public Result<List<SysRole>> getRolesList(Integer userId) {
        Result<List<SysRole>> result = new Result<>();
        List<SysRole> roleList = sysUserService.getRolesList(userId);
        result.setCode(Result.SUCCESS);
        result.setData(roleList);
        return result;
    }
    
    @RequestMapping("/saveRoles")
    @ResponseBody
    public Result<String> saveRoleResource(Integer userId, String rolesJson){

        SysUser user = sysUserService.findById(userId);
        
        sysUserService.clearRoles(user);
        
        List<SysRole> roles = user.getRoles();
        if (roles == null) {
        	roles = new ArrayList<SysRole>();
        	user.setRoles(roles);
        }
        
		JSONObject jsonObject = JSON.parseObject(rolesJson);
		 
		for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
			int roleId = Integer.parseInt(entry.getKey());
        	SysRole r = sysRoleService.findById(roleId);
        	if (r != null) {
        		roles.add(r);
        	}
		}
        
        sysUserService.insertRelation(user);
        
        Result<String> result = new Result<>();
        result.setCode(Result.SUCCESS);
        result.setMsg("保存成功");
        return result;
    }
    
//
//    @RequestMapping("/add")
//    @ResponseBody
//    public Result<String> add(SysUserPO po) {
//        Result<String> result = new Result<>();
//        int count = sysUserService.countByName(po);
//        if (count > 0) {
//            result.setCode(Result.FAIL);
//            result.setMsg(String.format("添加失败，用户名 \"%s\" 已存在", po.getName()));
//        } else {
//            po.setCreateTime(new Date());
//            sysUserService.insert(po);
//            result.setCode(Result.SUCCESS);
//            result.setMsg("添加成功");
//        }
//        return result;
//    }
//
//    @RequestMapping("/findById")
//    @ResponseBody
//    public Result<SysUserPO> findById(Integer id) {
//        Result<SysUserPO> result = new Result<>();
//        SysUserPO po = sysUserService.findById(id);
//        if (po == null) {
//            result.setCode(Result.FAIL);
//            result.setMsg(String.format("记录不存在！"));
//        } else {
//            result.setCode(Result.SUCCESS);
//            result.setData(po);
//        }
//
//        return result;
//    }
//
//    @RequestMapping("/del")
//    @ResponseBody
//    public Result<String> delete(Integer id) {
//        Result<String> result = new Result<>();
//        sysUserService.deleteById(id);
//        //删除权限
//        sysUserProductRoleService.deleteByUserId(id);
//        sysUserChannelServerLimitService.deleteByUserId(id);
//
//        result.setCode(Result.SUCCESS);
//        result.setMsg("删除成功!");
//        return result;
//    }
//
//    @RequestMapping("/edit")
//    @ResponseBody
//    public Result<String> edit(SysUserPO po) {
//        Result<String> result = new Result<>();
//        Integer id = po.getId();
//        if (id == null || id <= 0){
//            result.setCode(Result.FAIL);
//            result.setMsg("修改失败!");
//            return result;
//        }
//        SysUserPO oldPo = sysUserService.findById(id);
//        oldPo.setName(po.getName());
//        oldPo.setStatus(po.getStatus());
//        oldPo.setUserName(po.getUserName());
//        sysUserService.update(oldPo);
//        result.setCode(Result.SUCCESS);
//        result.setMsg("修改成功!");
//        return result;
//    }
//
//    @RequestMapping("/resetPassword")
//    @ResponseBody
//    public Result<String> resetPassword(SysUserPO po) {
//        Result<String> result = new Result<>();
//        Integer id = po.getId();
//        if (id == null || id <= 0){
//            result.setCode(Result.FAIL);
//            result.setMsg("重置密码失败!");
//        } else {
//            SysUserPO oldPo = sysUserService.findById(id);
//            oldPo.setPassword(po.getPassword());
//            sysUserService.resetPassword(oldPo);
//            result.setCode(Result.SUCCESS);
//            result.setMsg("重置密码成功!");
//        }
//        return result;
//    }
//
//    @RequestMapping("/userChannel")
//    @ResponseBody
//    public Result<List<ZTreeNode>> userChannel(Integer productId,Integer userId) {
//        int bigChannelIdAdd = 1000000;
//        int smallChannelIdAdd = 10000000;
//        Result<List<ZTreeNode>> result = new Result<>();
//        List<ZTreeNode> nodeList = new ArrayList<>();
//        List<BigChannel> bigChannelList = channelServerService.bigChannelList(productId);
//        List<SmallChannel> smallChannelList = channelServerService.smallChannelList(productId);
//        List<Channel> channelList = channelServerService.channelList(productId);
//        //Set<Integer> userChannelIds = channelServerService.userChannelIds(productId,userId);
//        Set<Integer> bigChannelIds,smallChannelIds,channelIds;
//        SysUserChannelServerLimitPO channelServerLimitPO = sysUserChannelServerLimitService.findByUserIdAndProductId(userId,productId);
//        if(channelServerLimitPO != null){
//            bigChannelIds = limitStrToSet(channelServerLimitPO.getBigChannels());
//            smallChannelIds = limitStrToSet(channelServerLimitPO.getSmallChannels());
//            channelIds = limitStrToSet(channelServerLimitPO.getChannels());
//        }else{
//            bigChannelIds = new HashSet<>();
//            smallChannelIds = new HashSet<>();
//            channelIds = new HashSet<>();
//        }
//        for(Channel channel : channelList){
//            ZTreeNode zTreeNode = new ZTreeNode();
//            zTreeNode.setId(channel.getId());
//            zTreeNode.setName(channel.getName());
//            if(channelIds.contains(channel.getId())){
//                zTreeNode.setChecked(true);
//                smallChannelIds.add(channel.getSmallChannelId());
//            }else{
//                zTreeNode.setChecked(false);
//            }
//            zTreeNode.setpId(channel.getSmallChannelId()+smallChannelIdAdd);
//            nodeList.add(zTreeNode);
//        }
//        for(SmallChannel smallChannel : smallChannelList){
//            ZTreeNode zTreeNode = new ZTreeNode();
//            zTreeNode.setId(smallChannel.getId()+smallChannelIdAdd);
//            zTreeNode.setName(smallChannel.getName());
//            if(smallChannelIds.contains(smallChannel.getId())){
//                zTreeNode.setChecked(true);
//                bigChannelIds.add(smallChannel.getBigChannelId());
//            }else{
//                zTreeNode.setChecked(false);
//            }
//            zTreeNode.setpId(smallChannel.getBigChannelId()+bigChannelIdAdd);
//            nodeList.add(zTreeNode);
//        }
//        for(BigChannel bigChannel : bigChannelList){
//            ZTreeNode zTreeNode = new ZTreeNode();
//            zTreeNode.setId(bigChannel.getId()+bigChannelIdAdd);
//            zTreeNode.setName(bigChannel.getName());
//            if(bigChannelIds.contains(bigChannel.getId())){
//                zTreeNode.setChecked(true);
//            }else{
//                zTreeNode.setChecked(false);
//            }
//            zTreeNode.setpId(0);
//            nodeList.add(zTreeNode);
//        }
//        result.setCode(Result.SUCCESS);
//        result.setData(nodeList);
//        return result;
//    }
//
//    @RequestMapping("/userServer")
//    @ResponseBody
//    public Result<List<ZTreeNode>> userServer(Integer productId,Integer userId) {
//        Result<List<ZTreeNode>> result = new Result<>();
//        List<ZTreeNode> nodeList = new ArrayList<>();
//        List<Server> serverList = channelServerService.serverList(productId);
//        SysUserChannelServerLimitPO channelServerLimitPO = sysUserChannelServerLimitService.findByUserIdAndProductId(userId,productId);
//        Set<Integer> serverIds;
//        if(channelServerLimitPO != null){
//            serverIds = limitStrToSet(channelServerLimitPO.getServers());
//        }else{
//            serverIds = new HashSet<>();
//        }
//        for(Server server : serverList){
//            ZTreeNode zTreeNode = new ZTreeNode();
//            zTreeNode.setId(server.getId());
//            zTreeNode.setName(server.getName());
//            if(serverIds.contains(server.getId())){
//                zTreeNode.setChecked(true);
//            }else{
//                zTreeNode.setChecked(false);
//            }
//            nodeList.add(zTreeNode);
//        }
//        result.setCode(Result.SUCCESS);
//        result.setData(nodeList);
//        return result;
//    }
//
//    @RequestMapping("/saveUserChannel")
//    @ResponseBody
//    public Result<String> saveUserChannel(SysUserChannelServerLimitPO po){
//        sysUserChannelServerLimitService.insertBigChannelLimit(po);
//        sysUserChannelServerLimitService.insertSmallChannelLimit(po);
//        sysUserChannelServerLimitService.insertChannelLimit(po);
//        Result<String> result = new Result<>();
//        result.setCode(Result.SUCCESS);
//        result.setMsg("保存成功");
//        return result;
//    }
//
//    @RequestMapping("/saveUserServer")
//    @ResponseBody
//    public Result<String> saveUserServer(SysUserChannelServerLimitPO po){
//        sysUserChannelServerLimitService.insertSeverLimit(po);
//        Result<String> result = new Result<>();
//        result.setCode(Result.SUCCESS);
//        result.setMsg("保存成功");
//        return result;
//    }
//
//
//    private Set<Integer> limitStrToSet(String str){
//        Set<Integer> set;
//        if(!StringUtils.isEmpty(str)){
//            String[] ids = StringUtils.split(str,",");
//            List<Integer> list = new ArrayList<>();
//            for(String id : ids){
//                list.add(Integer.parseInt(id));
//            }
//            set = new HashSet<>(list);
//        }else{
//            set = new HashSet<>();
//        }
//        return set;
//    }

}
